package com.cnvp.paladin.controller;

import java.io.File;
import java.net.URL;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;

import com.cnvp.paladin.core.BaseController;
import com.cnvp.paladin.kit.ConfigKit;
import com.cnvp.paladin.kit.PropertyKit;
import com.cnvp.paladin.kit.StringKit;
import com.cnvp.paladin.model.Sceneconfig;
import com.cnvp.paladin.model.SysNav;
import com.cnvp.paladin.model.SysUser;
import com.cnvp.paladin.model.SysUserRole;
import com.cnvp.paladin.service.NavService;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.JFinal;
import com.jfinal.kit.EncryptionKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

public class IndexController extends BaseController {
    public int issuperadmin() {
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        int userID = currentUser.get("id");
        return userID;
    }

    public void index() {
        List<SysNav> tree = NavService.getTreeMap(0);
        setAttr("tree", tree);
    }

    /**
     * @author WilliamLee
     * @date 2015年9月17日 下午9:41:27
     * 
     *       载入首页同时载入用户修改的头像
     */
    public void welcome() {
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        currentUser = SysUser.dao.findById(currentUser.get("id"));
        String cp = JFinal.me().getContextPath();
        setAttr("root", ("".equals(cp) || "/".equals(cp)) ? "" : cp);
        setAttr("url", currentUser.get("url") == null ? ConfigKit.get("default.portrait") : currentUser.get("url"));

    }

    public void profile() {
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        if ("POST".equals(getRequest().getMethod())) {
            if (getModel(SysUser.class, "user").set("id", currentUser.getInt("id")).update())
                redirect("/profile");
            return;
        }
        setAttr("data", SysUser.dao.findById(currentUser.getInt("id")));
    }

    public void profile_app() {
        Map<String, Object> json = new HashMap<String, Object>();
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        json.put("data", currentUser);
        renderJson(json);
    }

    public void closed() {
        setAttr("app_remark", PropertyKit.get("app_remark"));
        render("common/close.html");
    }

    @ClearInterceptor(ClearLayer.ALL)
    public void test() {
        List<String> actionKeys = JFinal.me().getAllActionKeys();
        for (String ak : actionKeys) {
            System.out.println(ak);
        }
        String cp = JFinal.me().getContextPath();
        setAttr("root", ("".equals(cp) || "/".equals(cp)) ? "" : cp);
        // List<SysDept> deptModels = new SysDept().findByModel();
        // TreeKit deptTree = new TreeKit();
        // deptTree.importModels(deptModels);
        // deptTree.getSelectMap();
        // renderNull();
    }

    public void portrait() {

        if ("POST".equals(getRequest().getMethod())) {
            // 获取上传的文件
            UploadFile pf1 = getFile("file");
            String image_name = getPara("image_name");
            // String filename2 = pf1.getFileName();
            System.out.println(pf1);
            System.out.println(image_name);
            if ( null != pf1 && !image_name.isEmpty()) {
                String file_exit = "jpg";
                String filename = image_name + "." + file_exit;
                // 获取服务器的路径
                URL url = IndexController.class.getResource("/");
                String getPath = url.getPath().substring(0, url.getPath().length() - 16);
                // 设置头像的路径
                String path = getPath + "Static/images/protrait/";
                String portrait = path + filename;
                File file = pf1.getFile();
                file.renameTo(new File(portrait));
                this.setAttr("fileName", portrait);
                // 更新数据库用户信息
                //SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
                int userID = issuperadmin();
                String sqlFind = "select * from cnvp_sys_user where id =" + "\"" + userID + "\";";
                List<Record> user = Db.find(sqlFind);
                //currentUser = SysUser.dao.findById(currentUser.get("id"));
                File deleteFile = new File(path + user.get(0).get("url") + ".jpg");
                if (deleteFile.exists() && !user.get(0).get("url").equals("504139779"))
                    deleteFile.delete();
                System.out.println("================fileName:" + portrait);
                // 以json格式进行渲染
                Db.update("cnvp_sys_user", user.get(0).set("url", image_name));
                //SysUser.dao.set("id", currentUser.get("id")).set("url", image_name).update();
                String is_app = getPara("is_app");
                if ("1".equals(is_app)) {
                    renderJson("{\"code\":\"0\",\"msg\":\"success\"}");
                } else {
                    alertAndGoback("修改头像成功！");
                }
            } else {
                renderJson("{\"code\":\"301\",\"msg\":\"缺少参数\"}");
            }
        }

    }

    public void portrait_download() {
        Map<String, Object> json = new HashMap<String, Object>();
        String is_app = getPara("is_app");
        SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        currentUser = SysUser.dao.findById(currentUser.get("id"));
        String image_name = currentUser.get("url");
        json.put("code", "0");
        json.put("data", image_name);
        json.put("msg", "success");
        if ("1".equals(is_app))
            renderJson(json);

    }

}
